package com.ruitu.mall_98_2.order;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.my_base.Config;
import com.beanu.arad.base.my_base.MyBaseActivity;
import com.beanu.arad.base.my_base.base_list.ListBaseAdapter;
import com.beanu.arad.base.my_base.base_list.SuperViewHolder;
import com.beanu.arad.utils.CalcUtils;
import com.beanu.arad.utils.Logg;
import com.beanu.arad.utils.TimeUtils;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.bumptech.glide.Glide;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.ruitu.mall_98_2.R;
import com.ruitu.mall_98_2.dao.APIRetrofit;
import com.ruitu.mall_98_2.mine.AddressListActivity;
import com.ruitu.mall_98_2.mvp.contract.CommitOrderContract;
import com.ruitu.mall_98_2.mvp.model.CommitOrderModel;
import com.ruitu.mall_98_2.mvp.presenter.CommitOrderPresenter;
import com.ruitu.router_module.A_Rutils;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.SubscriberImpl;
import com.ruitu.router_module.bean.mine.Address;
import com.ruitu.router_module.bean.mine.Coupon;
import com.ruitu.router_module.bean.order.CartSettlement;
import com.ruitu.router_module.bean.order.ConfirOrder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class CommitOrderActivity extends MyBaseActivity<CommitOrderPresenter, CommitOrderModel> implements CommitOrderContract.View {
    private CommitOrderAdapter adapter;
    private LRecyclerView lRecyclerView;
    private LinearLayout ll_address;
    private TextView tv_consignee;//收货人
    private TextView tv_tel;//电话
    private TextView tv_address;//地址
    private TextView tv_new_add_address;//新建地址
    private TextView tv_add;//备份地址
    private TextView tv_all_total;//总价
    private TextView tv_commodity_order;//提交订单

    private Address address;//地址列表
    private List<Integer> skipId = new ArrayList<>();

    private LRecyclerViewAdapter recyclerViewAdapter;
    private String ids;
    private int shopPosition;
    private int commodityPosition;
    private List<CartSettlement.ShopList> shopLists;
    private List<String> coupons = new ArrayList<>();
    private PopupWindow popupWindow;
    private CartSettlement cartSettlement;

    private String s;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!Arad.bus.isRegistered(this)) {
            Arad.bus.register(this);
        }
        setHeadTitle("填写订单");
        skipId.add(R.id.header);
        showEmptyView(skipId);
        coupons = new ArrayList<>();
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_commit_order;
    }

    @Override
    protected ProgressLayout findProgressLayout() {
        return findViewById(R.id.progress);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == ll_address) {
            Bundle bundle = new Bundle();
            bundle.putString("from", "from");
            startActivity(AddressListActivity.class, bundle);
        }

        if (v == tv_commodity_order) {
            String goodId = null;
            String couponId;
            String ids = null;
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < shopLists.size(); i++) {
                List<CartSettlement.GoodsList> goodsList = shopLists.get(i).getGoodsList();
                for (int j = 0; j < goodsList.size(); j++) {
                    CartSettlement.GoodsList goodsList1 = goodsList.get(j);
                    if (goodsList1.getModelType().equals("0")) {
                        goodId = goodsList1.getGoodId();
                    } else {
                        goodId = goodsList1.getGoodsModel().getId();
                    }

                    if (goodsList1.getCoupon() != null) {
                        couponId = goodsList1.getCoupon().getUserCouponId();
                    } else {
                        couponId = "0";
                    }
                    ids = buffer.append(goodId).append(":").append(couponId).append(",").toString();
                }
            }
            if (address == null) {
                ToastUtils.showShort("请添加收货地址");
                return;
            }
            showProgress();
            mPresenter.cartForOrder(AppHolder.instance().getUser().getAccountId(), ids, address.getId());
        }
    }

    @Override
    protected void initViews() {
        super.initViews();

        Bundle bundle = getIntent().getExtras();
        ids = bundle.getString("ids");
        getAddress();
        lRecyclerView = findViewById(R.id.lRecyclerView);

        View view = getLayoutInflater().inflate(R.layout.item_commit_order_header, null);
        ll_address = view.findViewById(R.id.ll_address);
        tv_consignee = view.findViewById(R.id.tv_consignee);
        tv_tel = view.findViewById(R.id.tv_tel);
        tv_add = findViewById(R.id.tv_address);
        tv_all_total = findViewById(R.id.tv_all_total);
        tv_address = view.findViewById(R.id.tv_address);
        tv_new_add_address = view.findViewById(R.id.tv_new_add_address);
        tv_commodity_order = findViewById(R.id.tv_commodity_order);
        RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
        lRecyclerView.setLayoutManager(manager);
        adapter = new CommitOrderAdapter(this);
        recyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        lRecyclerView.setAdapter(recyclerViewAdapter);
        recyclerViewAdapter.addHeaderView(view);
        lRecyclerView.setPullRefreshEnabled(false);
        setListener();

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 999) {
                double allTotal = 0;
                for (int j = 0; j < shopLists.size(); j++) {
                    double total = 0;
                    List<CartSettlement.GoodsList> goodsList = shopLists.get(j).getGoodsList();
                    for (int i = 0; i < goodsList.size(); i++) {
                        Coupon coupon = goodsList.get(i).getCoupon();
                        if (coupon != null) {
                            if (coupon.getStatus().equals("1")) {
                                Double multiply = CalcUtils.sub(goodsList.get(i).getTotalMoney(), CalcUtils.multiply(goodsList.get(i).getTotalMoney(), Double.parseDouble(coupon.getDiscountRatio()) / 100, 2, RoundingMode.HALF_UP));
                                total = CalcUtils.add(total, multiply);
                            } else {
                                Double sub = CalcUtils.sub(goodsList.get(i).getTotalMoney(), Double.parseDouble(coupon.getReduceMoney()));
                                total = CalcUtils.add(total, sub);
                            }
                        } else {
                            total = CalcUtils.add(total, goodsList.get(i).getTotalMoney());
                        }
                    }
                    allTotal = CalcUtils.add(allTotal, total);

                }
//                tv_all_total.setText("总金额: ￥"+CalcUtils.add(allTotal,cartSettlement.getFreightMoney()));
                tv_all_total.setText("实付款:  " + "￥" + CalcUtils.add(allTotal, cartSettlement.getFreightMoney()));
            }
        }
    };

    /**
     * 选取收货地址
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setAddresses(EventModel<Address> addresses) {
        if (addresses.getEventCode() == 18111600) {
            this.address = addresses.getEventObj();
            getData(address.getId());
        }
    }

    private void getData(String id) {
        mPresenter.cartSettlement(AppHolder.instance().getUser().getAccountId(), ids, id);
    }


    @Override
    public void setFails() {
        showError(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAddress();
            }
        });
    }

    @Override
    public void setSuc(CartSettlement commitOrder) {
        cartSettlement = commitOrder;
        if (!isDataEmpty(commitOrder.getGoodsList())) {
            showContent(null);
            shopLists = commitOrder.getGoodsList();
            initAddress();
            adapter.setDataList(commitOrder.getGoodsList());
        } else {
            showEmptyView(skipId);
        }
    }

    @Override
    public void setCoupon(List<Coupon> coupons) {
        showCouponDialog(coupons);
    }

    @Override
    public void setForOrder(ConfirOrder confirOrder) {
        Intent intent = new Intent(this, PayOrderActivity.class);
        intent.putExtra("confirOrder", confirOrder);
        startActivity(intent);
        finish();
    }

    private void initAddress() {
        if (address == null) {
            tv_new_add_address.setVisibility(View.VISIBLE);
        } else {
            tv_new_add_address.setVisibility(View.GONE);
            Logg.i(address.toString());
            tv_consignee.setText("收货人:" + address.getName());
//            String new_tel = address.getPhone().substring(0, 3) + "****" + address.getPhone().substring(6, 10);
            String new_tel = address.getPhone();
            tv_tel.setText(new_tel);
            s = address.getProvince() + address.getCity() + address.getCounty() + address.getAddress();
            tv_address.setText(s);
            tv_add.setText(s);
        }
        tv_all_total.setText("实付款:  " + " ￥" + cartSettlement.getTotalPrice());
    }

    class CommitOrderAdapter extends ListBaseAdapter<CartSettlement.ShopList> {

        public CommitOrderAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_commit_order;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_shop_name = holder.getView(R.id.tv_shop_name);
            TextView tv_subtotal_sum = holder.getView(R.id.tv_subtotal_sum);
            TextView tv_subtotal_price = holder.getView(R.id.tv_subtotal_price);
            ImageView iv_company_logo = holder.getView(R.id.iv_company_logo);
            View v_line = holder.getView(R.id.v_line);
            RecyclerView recyclerView = holder.getView(R.id.recyclerView);
            CartSettlement.ShopList shopList = mDataList.get(position);
            tv_shop_name.setText(shopList.getName());
            Glide.with(mContext).load(Config.BASE_URL + shopList.getCompanyImage()).apply(Arad.opts_shop).into(iv_company_logo);
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(mContext);
            recyclerView.setLayoutManager(layoutManager);
            CommodityAdapter adapter = new CommodityAdapter(mContext);
            recyclerView.setAdapter(adapter);
            List<CartSettlement.GoodsList> goodsList = shopList.getGoodsList();
            adapter.setDataList(goodsList);
            adapter.shopPositio = position;
            if (position == mDataList.size() - 1) {
                v_line.setVisibility(View.GONE);
            } else {
                v_line.setVisibility(View.VISIBLE);
            }
            double total = 0;
            for (int i = 0; i < goodsList.size(); i++) {
                Coupon coupon = goodsList.get(i).getCoupon();
                if (coupon != null) {
                    if (coupon.getStatus().equals("1")) {
                        Double multiply = CalcUtils.sub(goodsList.get(i).getTotalMoney(), CalcUtils.multiply(goodsList.get(i).getTotalMoney(), Double.parseDouble(coupon.getDiscountRatio()) / 100, 2, RoundingMode.HALF_UP));
                        total = CalcUtils.add(total, multiply);
                    } else {
                        Double sub = CalcUtils.sub(goodsList.get(i).getTotalMoney(), Double.parseDouble(coupon.getReduceMoney()));
                        total = CalcUtils.add(total, sub);
                    }
                } else {
                    total = CalcUtils.add(total, goodsList.get(i).getTotalMoney());
                }
            }
            if (total > 0) {
                tv_subtotal_price.setText(total + "元");
            } else {
                tv_subtotal_price.setText(shopList.getGoodsAllMoney() + "元");
            }

        }

    }

    /**
     * 商品的适配器
     */
    class CommodityAdapter extends ListBaseAdapter<CartSettlement.GoodsList> {
        public int shopPositio;

        public CommodityAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_cart_commit_commodity;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            ImageView iv_order_commodity_img = holder.getView(R.id.iv_order_commodity_img);
            TextView tv_commodity_name = holder.getView(R.id.tv_commodity_name);
            TextView tv_commodity_price = holder.getView(R.id.tv_commodity_price);
            TextView tv_commodity_num = holder.getView(R.id.tv_commodity_num);
            TextView tv_info = holder.getView(R.id.tv_info);
            TextView tv_coupon = holder.getView(R.id.tv_coupon);
            TextView tv_total_postage_price = holder.getView(R.id.tv_total_postage_price);
            RelativeLayout rl_coupon = holder.getView(R.id.rl_coupon);
            View line = holder.getView(R.id.line);
            if (position != 0) {
                line.setVisibility(View.VISIBLE);
            } else {
                line.setVisibility(View.GONE);
            }

            final CartSettlement.GoodsList goodsList = mDataList.get(position);
            Glide.with(mContext).load(Config.BASE_URL + goodsList.getImageUrl()).apply(Arad.opts).into(iv_order_commodity_img);
            tv_commodity_name.setText(goodsList.getGoodName());
            tv_commodity_price.setText("￥" + goodsList.getModelPrice());
            tv_commodity_num.setText("x" + goodsList.getCartGoodsNum());
            if (!TextUtils.isEmpty(goodsList.getSkuName())) {
                tv_info.setText(goodsList.getSkuName());
            } else {
                tv_info.setText("");
            }
            if (TextUtils.equals(goodsList.getGoodPostage(), "1")) {
                tv_total_postage_price.setText(goodsList.getFreightMoney() + "元");
            } else {
                tv_total_postage_price.setText("包邮");
            }

            Coupon coupon = goodsList.getCoupon();
            if (coupon != null) {
                tv_coupon.setTextColor(Color.parseColor("#bbff0000"));
                if (TextUtils.equals(coupon.getStatus(), "1")) {
                    tv_coupon.setText("优惠" + coupon.getDiscountRatio() + "%");
                } else {
                    tv_coupon.setText("满减" + coupon.getReduceMoney() + "元");
                }
            } else {
                if (goodsList.getCouponStatus().equals("0")) {
                    tv_coupon.setText("此商品不参加任何优惠");
                } else {
                    tv_coupon.setText("选取优惠券");
                }
            }

            rl_coupon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (goodsList.getCouponStatus().equals("0")) {
                        ToastUtils.showShort("此商品不参加任何优惠");
                        return;
                    }
                    shopPosition = shopPositio;
                    commodityPosition = position;
                    StringBuffer buffer = new StringBuffer();
                    String s = "0";
                    for (int i = 0; i < shopLists.size(); i++) {
                        List<CartSettlement.GoodsList> goodsList1 = shopLists.get(i).getGoodsList();
                        for (int j = 0; j < goodsList1.size(); j++) {
                            if (goodsList1.get(j).getCoupon() != null) {
                                s = buffer.append(goodsList1.get(j).getCoupon().getUserCouponId()).append(",").toString();
                            }
                        }
                    }
                    showProgress();
                    mPresenter.selectUseCoupons(AppHolder.instance().getUser().getAccountId(),
                            s, goodsList.getGoodId(), cartSettlement.getTotalPrice() + "", goodsList.getCompanyId());

                }
            });

        }
    }

    /**
     * 优惠券列表
     */
    private void showCouponDialog(List<Coupon> couponList) {
        View view = View.inflate(this, R.layout.item_coupon_dialog, null);
        popupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setContentView(view);
        ImageView iv_close = view.findViewById(R.id.iv_close);
        //领券中心
        TextView tv_coupon_redemption_centre = view.findViewById(R.id.tv_coupon_redemption_centre);
        LinearLayout ll_coupon_null = view.findViewById(R.id.ll_coupon_null);
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        DataAdapter adapter = new DataAdapter(this);
        recyclerView.setAdapter(adapter);
        if (isDataEmpty(couponList)) {
            ll_coupon_null.setVisibility(View.VISIBLE);
        } else {
            adapter.setDataList(couponList);
            ll_coupon_null.setVisibility(View.GONE);
        }

        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        tv_coupon_redemption_centre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    A_Rutils.startActivity(CommitOrderActivity.this, "com.ruitu.mall_98_1.product.activity.CouponListPlatformActivity");
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });

        //设置背景半透明色
        backgroundAlpha(0.5f);
        //popupWindow  事件监听
        popupWindow.setOnDismissListener(new PopupDismissListener());
        View rootView = LayoutInflater.from(CommitOrderActivity.this).inflate(R.layout.activity_add_address, null);
        //将PopupWindow置于activity的底部
        popupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);

    }

    /**
     * 获取收货地址
     */
    private void getAddress() {
        showProgress();
        final String accountId = AppHolder.instance().getUser().getAccountId();
        APIRetrofit.getDefault().getMineAddress(accountId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new SubscriberImpl<BaseResult<List<Address>>>() {
                    @Override
                    public void onError(Throwable e) {
                        hideProgress();
                        e.printStackTrace();
                        showError(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                getAddress();
                            }
                        });
                    }

                    @Override
                    public void onNext(BaseResult<List<Address>> listBaseResult) {
                        if (listBaseResult.isSuccess()) {
                            if (!isDataEmpty(listBaseResult.getData())) {
                                address = listBaseResult.getData().get(0);
                            }
                            if (address != null) {
                                getData(address.getId());
                            } else {
                                getData("");
                            }
                        }
                    }
                });
    }

    private void setListener() {
        ll_address.setOnClickListener(this);
        tv_commodity_order.setOnClickListener(this);
        final int height = ll_address.getHeight();
        /**
         * 地址滑动
         */
        lRecyclerView.setLScrollListener(new LRecyclerView.LScrollListener() {
            @Override
            public void onScrollUp() {

            }

            @Override
            public void onScrollDown() {

            }

            @Override
            public void onScrolled(int distanceX, int distanceY) {
                if (distanceY > height) {
                    if (!TextUtils.isEmpty(s)) {
                        tv_add.setVisibility(View.VISIBLE);
                    }
                } else {
                    tv_add.setVisibility(View.GONE);
                }
            }

            @Override
            public void onScrollStateChanged(int state) {

            }
        });
    }

    class DataAdapter extends ListBaseAdapter<Coupon> {

        public DataAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_coupon;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            TextView tv_sum = holder.getView(R.id.tv_sum);
            TextView tv_user_type = holder.getView(R.id.tv_user_type);
            TextView tv_user_restrict = holder.getView(R.id.tv_user_restrict);
            TextView tv_useful_life = holder.getView(R.id.tv_useful_life);
            LinearLayout ll_immediate_use = holder.getView(R.id.ll_immediate_use);
            final Coupon coupon = mDataList.get(position);
            if (TextUtils.equals(coupon.getStatus(), "1")) {
                tv_sum.setText(coupon.getDiscountRatio() + "%");
                tv_user_restrict.setText("企业内商品优惠" + coupon.getDiscountRatio() + "%");
            } else {
                tv_sum.setText("￥" + coupon.getReduceMoney());
                tv_user_restrict.setText("订单金额满" + coupon.getSatisfyMoney() + "元可使用");
            }

            if (TextUtils.equals(coupon.getType(), "1")) {
                tv_user_type.setText("全类商品通用");
            } else {
                if (TextUtils.isEmpty(coupon.getCompanyName())) {
                    if (TextUtils.equals(coupon.getShopType(), "1")) {
                        tv_user_type.setText(coupon.getGoodsName());
                    } else {
                        tv_user_type.setText(coupon.getCompanyName());
                    }
                } else {
                    tv_user_type.setText(coupon.getCompanyName());
                }
            }
            tv_useful_life.setText("有效期:" + TimeUtils.millis2String(Long.parseLong(coupon.getCreateTime()), new SimpleDateFormat("yyyy-MM-dd")) + " " + TimeUtils.millis2String(Long.parseLong(coupon.getUseTime()), new SimpleDateFormat("yyyy-MM-dd")));

            ll_immediate_use.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    shopLists.get(shopPosition).getGoodsList().get(commodityPosition).setCoupon(coupon);
                    coupons.add(coupon.getId());
                    adapter.setDataList(shopLists);
                    if (popupWindow != null) {
                        popupWindow.dismiss();
                    }
                    handler.sendEmptyMessage(999);
                }
            });
        }
    }

    class PopupDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            backgroundAlpha(1f);
        }
    }

    private void backgroundAlpha(float v) {
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.alpha = v;
        getWindow().setAttributes(layoutParams);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        getAddress();
    }
}
